<?php

namespace Kyle\Http;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\GuzzleException;
use Kyle\Http\exception\InvalidConfigException;

class Client
{

    /**
     * @var self
     */
    private static $instance = null;

    /**
     * @var HttpClient
     */
    private $httpClient = null;

    /**
     * @param array $options = [
     * 'base_uri' => '',
     * 'verify'   => false,
     * 'timeout'  => 5,
     * 'headers'  => []
     * ]
     * @return Client
     * @throws InvalidConfigException
     */
    public static function getInstance(array $options): Client
    {
        if (!isset($options['base_uri']) || !$options['base_uri']) {
            throw new InvalidConfigException('invalid base_uri');
        }
        static::$instance = new static();
        static::$instance->httpClient = new HttpClient($options);
        return static::$instance;
    }

    /**
     * get请求
     * @param string $uri
     * @param array $data
     * @return string
     * @throws GuzzleException
     */
    public function get(string $uri, array $data): string
    {
        $response = $this->httpClient->get($uri,[
            'query' => $data
        ]);
        return $response->getBody()->getContents();
    }

    /**
     * post请求
     * @param string $uri
     * @param array $data
     * @return string
     * @throws GuzzleException
     */
    public function post(string $uri,array $data): string
    {
        $response = $this->httpClient->post($uri,[
            'form_params' => $data
        ]);
        return $response->getBody()->getContents();
    }

    /**
     * json数据格式请求
     * @param string $uri
     * @param array $data
     * @param string $method
     * @return string
     * @throws GuzzleException
     */
    public function sendJson(string $uri, array $data, string $method = 'GET'): string
    {
        $response = $this->httpClient->request($method,$uri,[
            'json' => $data
        ]);
        return $response->getBody()->getContents();
    }
}